import {Injectable, NotFoundException} from "@nestjs/common";
import {InjectRepository} from "@nestjs/typeorm";
import {TaskEntity} from "./task.entity";
import {Between, Repository} from "typeorm";
import {v4 as uuidv4} from "uuid";
import {IPaginationOptions, paginate} from "nestjs-typeorm-paginate";
import * as dayjs from 'dayjs';

@Injectable()
export class TaskService {
  constructor(
    @InjectRepository(TaskEntity)
    private readonly taskModel: Repository<TaskEntity>
  ) {
  }

  public async pageQuery(params: any) {
    const {
      skip,
      take,
      sortBy = "createdAt",
      descending = "DESC",
      ...where
    } = params;
    const q = this.taskModel.createQueryBuilder("t");
    q.where(where);
    q.andWhere({createdAt: Between(dayjs().startOf('day'), dayjs().endOf('day'))})
    q.addOrderBy('t.done', 'ASC')
    q.leftJoinAndSelect('t.user', 'user');
    const options: IPaginationOptions = {limit: take, page: skip};
    return paginate<any>(q, options);
  }

  /**
   * 通过 ID 删除 Entity
   * @param id
   */
  public async removeById(id: string) {
    const tasks = await this.taskModel.findOne({id});
    if (!tasks) {
      throw new NotFoundException();
    }

    await this.taskModel.remove([tasks]);
    return true;
  }

  /**
   * 更新数据
   * @param updateEntity
   */
  public async update(updateEntity) {
    const tasks = await this.taskModel.findOne({
      id: updateEntity.id,
    });
    if (!tasks) {
      throw new NotFoundException();
    }

    await this.taskModel.update({id: updateEntity.id}, updateEntity);
    return true;
  }

  /**
   * 添加数据
   * @param insertEntity
   */
  public async insert(insertEntity) {
    insertEntity.id = uuidv4();
    insertEntity.createdAt = new Date();
    insertEntity.updatedAt = new Date();
    await this.taskModel.insert(insertEntity);
    return true;
  }

  public async batchRemove(ids: string[]) {
    const models = await this.taskModel.findByIds(ids);
    await this.taskModel.remove(models);
    return true;
  }
}
